<?
error_reporting( E_ALL );

ob_start(); // start output buffering so we don't use javascript to forward
session_start(); // will start a new session, or continue the current session
define( 'SAKE_ROOT', dirname('.') );
header("Cache-control: private"); // IE 6 Fix

// there is a staggering number of files being included here (it is organized, though)
require_once SAKE_ROOT.'/config/config.php';
require_once SAKE_ROOT.'/vendor/sake/birupack/lib/biru_controller.php';
require_once SAKE_ROOT.'/vendor/sake/birupack/lib/biru_view.php';
require_once SAKE_ROOT.'/vendor/sake/birurecord/lib/biru_record.php';
require_once SAKE_ROOT.'/app/controllers/application.php';

list( $page, $action ) = array( get( $rr, 'page', $default_page ), get( $rr, 'action', $default_action ) );
$class = ucfirst( strtolower( $page ) ).'Controller';

if( file_exists( SAKE_ROOT.'/app/controllers/'.strtolower( $page ).'.php' ) )
{
	require_once SAKE_ROOT.'/app/controllers/'.strtolower( $page ).'.php';
	@include_once SAKE_ROOT.'/app/helpers/'.strtolower( $page ).'_helper.php';
}
if( !class_exists( $class ) )
{
	throw new Exception('Undefined controller: '.$class );
}

$ctrl = new $class( $page_title, $baseimagedir, ( $default_layout ? $default_layout : 'default' ) );
if( method_exists( $ctrl, $action ) )
{
	// -- controller itself is executed here -- //
	apply_filters( $ctrl, $action, $ctrl->get_before_filters(), $ctrl->get_after_filters() );
	// ---------------------------------------- //	

	//-----------------------------//
	if( $ctrl->should_forward() )
	{
		// carry the flash along for the next request
		$_SESSION['__flash'] = serialize( $ctrl->get_flash() );
		header('Location: '.$ctrl->get_forward_to() );
	}
	//-----------------------------//
	
	extract( $ctrl->properties() );
	$flash = isset( $_SESSION['__flash'] ) ? unserialize( $_SESSION['__flash'] ) : null;
	
	// uncomment for diagnostic mode
	// echo '<small><pre>'; print_r( $_SESSION ); echo '</pre></small>';

	$controller = &$ctrl;
	$content_for_layout = render( $page, $action );
	echo render( 'layouts', strtolower( $ctrl->get_default_layout() ) );
}
else
{
	throw new Exception('Undefined action: '.$action );
}
$_SESSION['__flash'] = serialize( $ctrl->get_flash() );
ob_end_flush();
?>
